#include "eeprom.h"

#define I2C_DELAY() delay_us(1)

void EEPROM_Init(eeprom_data_t* eeprom_data)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_APB2PeriphClockCmd(EE_PIN_CLK, ENABLE);

    GPIO_InitStructure.GPIO_Pin = EE_SCL_PIN | EE_SDA_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    EE_SCL_HIGH;
    EE_SDA_HIGH;
    
    if(EEPROM_Read(EE_DATA_INIT) == 0xff)   //eeprom没有初始化
    {
        EEPROM_ContinuousWrite(EE_DATA_START, (uint8_t *)eeprom_data, sizeof(eeprom_data_t));
        EEPROM_Write(EE_DATA_INIT, 0x00);
    }
    else	//读取eeprom数据
	{
        EEPROM_ContinuousRead(EE_DATA_START, (uint8_t *)eeprom_data, sizeof(eeprom_data_t));
	}
}

void I2C_Start(void)
{
    EE_SDA_HIGH;
    EE_SCL_HIGH;
    I2C_DELAY();

    EE_SDA_LOW;
    I2C_DELAY();

    EE_SCL_LOW;
    I2C_DELAY();
}

void I2C_Stop(void)
{
    EE_SDA_LOW;
    EE_SCL_HIGH;
    I2C_DELAY();

    EE_SDA_HIGH;
    I2C_DELAY();
}

void I2C_SendByte(uint8_t data)
{
    uint8_t i;

    for (i = 0; i < 8; i++)
    {
        if ((data & 0x80) == 0x80)
        {
            EE_SDA_HIGH;
        }
        else
        {
            EE_SDA_LOW;
        }

        EE_SCL_HIGH;
        I2C_DELAY();

        EE_SCL_LOW;
        I2C_DELAY();

        data <<= 1;
    }

    EE_SDA_HIGH;
    I2C_DELAY();

    EE_SCL_HIGH;
    I2C_DELAY();

    EE_SCL_LOW;
    I2C_DELAY();
}

uint8_t I2C_ReceiveByte(void)
{
    uint8_t i, data = 0;

    EE_SDA_HIGH;

    for (i = 0; i < 8; i++)
    {
        EE_SCL_HIGH;
        I2C_DELAY();

        data <<= 1;
        if (EE_SDA_READ)
        {
            data |= 0x01;
        }

        EE_SCL_LOW;
        I2C_DELAY();
    }

    return data;
}

void EEPROM_Write(uint8_t addr, uint8_t data)
{
    I2C_Start();
    I2C_SendByte(EE_WRITE);
    I2C_SendByte(addr);
    I2C_SendByte(data);
    I2C_Stop();
}

uint8_t EEPROM_Read(uint8_t addr)
{
    uint8_t data;

    I2C_Start();
    I2C_SendByte(EE_WRITE);
    I2C_SendByte(addr);
    I2C_Start();
    I2C_SendByte(EE_READ);
    data = I2C_ReceiveByte();
    I2C_Stop();

    return data;
}

void EEPROM_ContinuousWrite(uint8_t addr, uint8_t* data, uint8_t lenth)
{
    for(uint8_t i=0; i<lenth; i++)
    {
        EEPROM_Write(addr+i, data[i]);
        delay_ms(5);    //连续写入时需延时让eeprom写入非掉电易失区
    }
}

void EEPROM_ContinuousRead(uint8_t addr, uint8_t* data, uint8_t lenth)
{
    for(uint8_t i=0; i<lenth; i++)
    {
        data[i] = EEPROM_Read(addr+i);
    }
}
